﻿using System;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;

namespace TodayYongxing
{
    public class Logger
    {
        public static void Log(Exception ex)
        {
            var msg = (ex.InnerException ?? ex).Message;
            Log(string.Format("\r\n发生错误：\r\n{0}", msg));
        }

        /// <summary>
        /// 记录执行日志。
        /// </summary>
        /// <param name="content"></param>
        public static void Log(string content)
        {
            if (ConfigurationManager.AppSettings.AllKeys.Contains("IsLog"))
            {
                var logSql = ConfigurationManager.AppSettings["IsLog"];
                if (!string.IsNullOrEmpty(logSql) && logSql.ToLower() == "true")
                {
                    Write(
                        string.Format("\r\n\r\n执行时间：{0}\r\n{1}", DateTime.Now.ToString(CultureInfo.InvariantCulture),
                                      content), LogType.Exec);
                }
            }
        }
        /// <summary>
        /// 写入日志内容。
        /// </summary>
        /// <param name="content"></param>
        /// <param name="type"></param>
        private static void Write(string content, LogType type)
        {
            try
            {
                var logsRoot = string.Format(@"{0}\{1}", AppDomain.CurrentDomain.BaseDirectory, "Logs");
                if (!Directory.Exists(logsRoot))
                {
                    Directory.CreateDirectory(logsRoot);
                }
                var errorsRoot = string.Format(@"{0}\{1}", AppDomain.CurrentDomain.BaseDirectory, @"Logs\errors");
                if (!Directory.Exists(errorsRoot))
                {
                    Directory.CreateDirectory(errorsRoot);
                }
                var execsRoot = string.Format(@"{0}\{1}", AppDomain.CurrentDomain.BaseDirectory, @"Logs\execs");
                if (!Directory.Exists(execsRoot))
                {
                    Directory.CreateDirectory(execsRoot);
                }
                var logDirectory = type == LogType.Error ? errorsRoot : execsRoot;
                var todayLogFile = string.Format(@"{0}\{1}.txt", logDirectory, DateTime.Now.ToString("yyyy-MM-dd"));

                using (var sw = File.AppendText(todayLogFile))
                {
                    try
                    {
                        sw.Write(content);
                    }
                    finally
                    {
                        sw.Close();
                    }

                }
            }
            catch
            {
                // 写日志发生错误，不抛异常，以避免程序无法往下执行。
            }
        }
    }

    public enum LogType
    {
        Error,
        Exec
    }
}